import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor
} from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

import { Reflector } from '@nestjs/core'

interface Data<T> {
  data: T
}

@Injectable()
export class ResponseInterceptor<T = any> implements NestInterceptor {
  constructor(private readonly reflector: Reflector) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<Data<T>> {
    const prefixMsg = this.reflector.get<string>(
      'prefixMsg',
      context.getHandler()
    )
    console.log('prefixMsg', prefixMsg)

    return next.handle().pipe(
      map((data) => {
        return {
          data,
          code: 0,
          message: prefixMsg ? `${prefixMsg}成功` : '操作成功'
        }
      })
    )
  }
}
